package tianrun.ziguan.api.calculate.config.service.template.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import org.springframework.stereotype.Service;
import tianrun.ziguan.api.calculate.config.dao.TTemplateMapper;
import tianrun.ziguan.api.calculate.config.entity.TTemplate;
import tianrun.ziguan.api.calculate.config.entity.TTemplateGroup;
import tianrun.ziguan.api.calculate.config.service.template.ITTemplateService;
import tianrun.ziguan.api.calculate.config.service.template.group.ITTemplateGroupService;
import tianrun.ziguan.api.calculate.config.utils.CollectionUtil;
import tianrun.ziguan.api.common.util.ListUtil;

import java.util.*;
import java.util.LinkedHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author zhaoqi
 */
@Service
public class TTemplateServiceImpl extends ServiceImpl<TTemplateMapper, TTemplate> implements ITTemplateService {
    private final ITTemplateGroupService templateGroupService;

    public TTemplateServiceImpl(ITTemplateGroupService templateGroupService) {
        this.templateGroupService = templateGroupService;
    }


    @Override
    public List<TTemplate> queryListByGroupId(Collection<Long> ids) {
        if (ListUtil.isEmpty(ids)) return Lists.newArrayList();
        return list(Wrappers.<TTemplate>lambdaQuery().in(TTemplate::getTemplateGroupId, ids));
    }

    @Override
    public List<TTemplate> getByIds(Set<Long> ids) {
        if (CollectionUtil.isEmpty(ids)) return Collections.emptyList();
        return list(Wrappers.<TTemplate>lambdaQuery().in(TTemplate::getId, ids));

    }

    @Override
    public JSONArray selection() {
        List<TTemplateGroup> groups = templateGroupService.list();
        Map<Long, TTemplateGroup> groupMap = groups.stream().collect(Collectors.toMap(TTemplateGroup::getId, Function.identity(), (k1, k2) -> k1));
        List<TTemplate> templates = list();
        Map<Long, List<TTemplate>> groupTemplateMap = ListUtil.groupList(templates, TTemplate::getTemplateGroupId);
        JSONArray jsonArray = new JSONArray();
        groupTemplateMap.forEach((groupId, tTemplates) -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("templateType", groupMap.get(groupId).getName());
            List<JSONObject> objects = tTemplates.stream().map(template -> {
                JSONObject object = new JSONObject();
                object.put("templateId", template.getId());
                object.put("templateName", template.getName());
                return object;
            }).collect(Collectors.toList());
            jsonObject.put("template", objects);
            jsonArray.add(jsonObject);
        });
        return jsonArray;
    }
}
